package com.jill.Service.impl;

import com.jill.Mapper.ArticleMapper;
import com.jill.Pojo.Article;
import com.jill.Service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

@Component
public class ArticleParseURL implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public List<Article> index(){
        List<Article>result=new ArrayList<>();

        articleMapper.index().forEach((object)->{

            StringBuilder sb=new StringBuilder();

            try {
                URL url=new URL(object.getContent());

                URLConnection conn=url.openConnection();

                InputStream is=conn.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(is));

                String line;

                while ((line=br.readLine())!=null){
                    sb.append(line).append("\n");
                }

                object.setContent(sb.toString());

                br.close();

                is.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }

            result.add(object);
        });
        return result;
    }

    @Override
    public List<Article> findByCate(Integer id) {

        List<Article>result=new ArrayList<>();

        articleMapper.findByCate(id).forEach((object)->{

            StringBuilder sb=new StringBuilder();

            try {
                URL url=new URL(object.getContent());

                URLConnection conn=url.openConnection();

                InputStream is=conn.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(is));

                String line;

                while ((line=br.readLine())!=null){
                    sb.append(line).append("\n");
                }

                object.setContent(sb.toString());

                br.close();

                is.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }

            result.add(object);
        });
        return result;

    }

    @Override
    public String addCount(Integer id) {
        articleMapper.addCount(id);

        return "ok";
    }

    @Override
    public List<Article> hotArticle() {
        List<Article> articles = articleMapper.hotArticle();

        return articles;
    }
}
